package hello;

import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class TranslateController {

    private static final Logger logger = LogManager.getLogger(TranslateController.class);

    @Autowired
    private TtranslateProperties properties;
    private final Map<String, TmtClient> clients = new HashMap<String, TmtClient>();

    // ResponseEntity<TextTranslateResponse> trans(@RequestBody TransReqBody reqbody) {
    @RequestMapping(value = "/trans", method = RequestMethod.POST)
    ResponseEntity<String> trans(@RequestParam(value="to", defaultValue="zh") String to, @RequestParam(value="text") String text) {
        try{
            Map<String, String> ticketMap = properties.getNextTicket();
            if (ticketMap.get("name").equals("zhao"))
                logger.warn("ticketMap zhao");

            if (!clients.containsKey(ticketMap.get("name"))) {
                Credential cred = new Credential(ticketMap.get("secretId"), ticketMap.get("secretKey"));
                TmtClient client = new TmtClient(cred, "ap-guangzhou");
                clients.put(ticketMap.get("name"), client);
            }

            TmtClient client = clients.get(ticketMap.get("name"));
            String result = TransInner(client, text, to, 0);

            if (result == null)
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("result null");

            return ResponseEntity.ok().body(result);
        } catch (Exception e) {
            logger.error("Exception: " + e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).body(e.getMessage());
        }
    }

    private String TransInner(TmtClient client, String text, String to, int trytimes)  throws TencentCloudSDKException {
        try {
            TextTranslateRequest req = new TextTranslateRequest();
            req.setProjectId(10133194);
            req.setSource("en");
            req.setTarget(to);

            if (text.startsWith("@")) {
                text = text.substring(1);
            } // fix sdk bug.

            req.setSourceText(text);
            // req.setSourceText(String.join(" ", reqbody.getArrayTexts()));

            client.getClientProfile().getHttpProfile().setConnTimeout(10);
            TextTranslateResponse resp = client.TextTranslate(req);

            return resp.getTargetText();
        } catch (TencentCloudSDKException e) {
            //if (e.getMessage().contains("Retry your request") && trytimes < 3) {
            //    logger.error("TransInner try: " + trytimes);
            //    return TransInner(client, text, to, ++trytimes);
            //}
            logger.error("TencentCloudSDKException: " + e.getMessage(), e);
            return null;
        }
    }
}
